<template>
 <div class="flex  w-full justify-center h-full" >
   <div style="width:600px;" class="flex flex-col bg-white h-full ">
    <div class=" p-3 flex justify-between items-center shadow">
        <div class="flex">
          <div class="text-lg font-bold "> <Icon icon="ant-design:reddit-outlined" size="24"/></div>
          <div class="text-lg font-bold ml-2">DEECP智能体</div>
        </div>
        <div class="flex mr-4 text-gray-500">
            内容由AI生成,无法确保真实准确，仅供参考
        </div>
         
    </div>
    <div class="flex flex-grow flex-col" style="height:300px;overflow:auto;" ref="scrollContainer">
       
       <div v-for="item in items" :key="item.id">
          <div class="flex justify-start m-3 " v-if="item.type=='bot'">
              <div class="flex m-2">
              <Avatar size="24" src="https://lf6-appstore-sign.oceancloudapi.com/ocean-cloud-tos/FileBizType.BIZ_BOT_ICON/default_bot_icon4.png?lk3s=50ccb0c5&x-expires=1736848914&x-signature=HyDRm62%2FJHvMnAy3cUXfItvJiIM%3D"/>
              </div>
              <div class="flex  flex-col ml-3">
                  <div class="flex items-start text-xs">DEECP</div>
                  <div class="flex p-2 items-center rounded-lg bg-gray-200">
                      <div v-html="item.content"></div>
                  </div>
               </div>
          </div>
          <div class="flex justify-end m-3 " v-else>
             
              <div class="flex  flex-col ml-3">
                  <div class="flex items-start justify-end text-xs">{{userinfo.userName}}</div>
                  <div class="flex p-2 items-center rounded-lg bg-gray-300">
                      <div v-html="item.content"></div>
                  </div>
               </div>
                <div class="flex m-2">
              <Avatar size="24" :src="userinfo.avatarUrl"/>
              </div>
          </div>

           
       </div>
       

    </div>
    <div class="flex flex-col items-end m-4">
        <div class="flex justify-between items-center w-full mb-3">
          <div class="ml-4 flex flex-1 text-gray-500">
              剩余对话次数:{{remainChartCount}}
          </div>
          <div class="flex">
            <a-button type="link" v-for="item in aiinfolist" :key="item.id" @click="goorderpage(item)">{{item.jiage}}元购买{{item.count}}次</a-button>
            
          </div>
        </div>
        <div class="flex justify-between w-full">
          <div class="font-bold ml-4 flex flex-1">
              <a-input v-model:value="query" placeholder="请输入与智能体对话内容" @pressEnter="quickChat"/>
          </div>
          <div style="margin-left: .5em;">
              <a-button @click="quickChat" :disabled="getBtnViable" :title="getTip">发送</a-button>
          </div>
        </div>
    </div>
   
  
    <!-- 订单抽屉-->
   <a-modal
        centered="true"
        :footer="null"
        width="40%"
        :closable="false"
        :maskClosable="false"
        v-model:visible="visibleD"
        :destroyOnClose="true"
        :after-visible-change="afterVisibleChange">
      <template #title>
          <span style="font-weight: 500; font-size:16px;padding:8px;">订单支付</span>
      </template>
      <OrdercrateAndPay ref="orderRef"  :preorderInfo="preorderInfo"  :status="status"  @changeorderstatus="changeorderstatus" @orderpaysuccess="orderpaysuccess"/>
  </a-modal>

  </div>
  </div>
</template>
<script lang="ts">
import { Popover} from 'ant-design-vue';
import { ShoppingCartOutlined, DeleteOutlined} from '@ant-design/icons-vue';
import { ref,defineComponent ,computed,reactive ,onMounted, nextTick} from 'vue';
import { useUserStore } from '/@/store/modules/user';
 import { Avatar ,Modal} from 'ant-design-vue';
import { getUserCartList,clearallUserCart,removeCartById ,precreateOrder } from '/@/api/dp/dpbaseapi';

import { difyStream } from '/@/api/dp/chatai/dpChatai';

import OrdercrateAndPay from '/@/views/dp/userorder/ordercreate.vue';
import { CozeAPI, COZE_CN_BASE_URL, ChatStatus, RoleType ,ChatEventType,type CreateChatData} from '@coze/api'
import { ailist,jianAicount} from '/@/api/dp/dpbaseapi';
import { dataTool } from 'echarts';
export default defineComponent({
  components: {
   AModal:Modal,
    ShoppingCartOutlined, 
    DeleteOutlined
  },
});
</script>

<script lang="ts" setup>  
const userStore = useUserStore();
var userinfo= userStore.getUserInfo||{};

const query=ref("");
const aiinfolist=ref([]);
const aicount=ref(0);
const usagecount = ref(0);
const freecount = ref(0)
const ischating=ref(false);

const remainChartCount = computed(()=>{
  let count = aicount.value;
  if(freecount.value>0 && usagecount.value<freecount.value) {
    count+=freecount.value - usagecount.value;
  }
  return count
})

 const getBtnViable = computed(() =>{
  if(query.value.trim().length==0
    ||(aicount.value==0&&freecount.value==0 || aicount.value==0&&usagecount.value>freecount.value)
    ||ischating.value){
    return true;
  }
  return false;
 });

 const getTip = computed(()=>{
    if(aicount.value==0&&freecount.value==0 || aicount.value==0&&usagecount.value>freecount.value) {
      return '对话次数使用完毕，请购买!';
    }
    return '点击发送';
  })

onMounted(() => {
  initWebsocket()
  getAiList();
});

 async function getAiList() {
  const res= await ailist();
  aiinfolist.value=res.list;
  aicount.value=res.aicount;
  freecount.value = res.freecount;
  usagecount.value = res.usagecount
 } 
const items=ref([]);
// const client = new CozeAPI({
//   token: 'pat_fl8vWXFlokJQhVLfjPfu2wuwhb7GibSxCklb5Daffapc13jerjdtXIgf0ZfeT6uZ', // Get your PAT from https://www.coze.com/open/oauth/pats
//   baseURL: COZE_CN_BASE_URL,
//   allowPersonalAccessTokenInBrowser: true
// });

// async function streamingChat(callback?: (v: CreateChatData) => void) {
//   const v = await client.chat.stream({
//     bot_id: '7506079354162970661',
//     auto_save_history: false,
//     additional_messages: [
//       {
//         role: RoleType.User,
//         content: query.value,
//         content_type: 'text',
//       },
//     ],
//   });
//   items.value.push({type:'user',content:query.value});
//   items.value.push({type:'bot',content:''})
//   ischating.value=true;
//   query.value="";
//    scrollToBottom();
//    //调用减少次数的方法
//   for await (const part of v) {
//     if (part.event === ChatEventType.CONVERSATION_CHAT_CREATED) {
//       callback && callback(part.data);
//     } else if (part.event === ChatEventType.CONVERSATION_MESSAGE_DELTA) {
//        items.value[items.value.length-1].content +=part.data.content
//         scrollToBottom();
//     } else if (part.event === ChatEventType.CONVERSATION_MESSAGE_COMPLETED) {
//       const { role, type, content } = part.data;
//       if (role === 'assistant' && type === 'answer') {
//         items.value[items.value.length-1].content +='<br/>'
//         scrollToBottom();
//       } else {
//         console.log('[%s]:[%s]:%s', role, type, content);
//       }
//     } else if (part.event === ChatEventType.CONVERSATION_CHAT_COMPLETED) {
//       console.log(part.data.usage);
//     } else if (part.event === ChatEventType.DONE) {
//       console.log(part.data);
//        ischating.value=false;
//     } else if (part.event === ChatEventType.ERROR) {
//       console.error(part.data);
//       ischating.value=false;
//     }
//   }
// }

// async function nonStreamingChat() {
//   const v = await client.chat.createAndPoll({
//     bot_id: '7455694818217017353',
//     additional_messages: [
//       {
//         role: RoleType.User,
//         content: query.value,
//         content_type: 'text',
//       },
//     ],
//   });
//   if (v.chat.status === ChatStatus.COMPLETED) {
//     for (const item of v.messages || []) {
//       console.log('[%s]:[%s]:%s', item.role, item.type, item.content);
//       if(item.type=='answer'){
//         //alert(item.content);
//         items.value.push({content:item.content})
//       }
//     }
//     console.log('usage', v.chat.usage);
//   }
// }
const ws = ref();
const char_index = ref(0);
const full_context = ref('')

function initWebsocket() {
  ws.value = new WebSocket("/js/a/dify/123")
  ws.value.onopen = ()=>{
    console.log('onopen...')
  }
  ws.value.onclose = ()=>{
    console.log('onclose...')
  }

  ws.value.onmessage = (message)=>{
    // if(message.data.indexOf('\n\n')>0) {
    //   items.value[items.value.length-1].content += '<br/><br/>';
    // } else if(message.data.indexOf('\n')>0) {
    //   items.value[items.value.length-1].content += '<br/>';
    // }
    let data = message.data;
    data = data.replace('\n\n', '<br/><br/>')
    data = data.replace('\n', '<br/>')
    full_context.value = full_context.value+data;
    tap()
    scrollToBottom();
  }

  ws.value.onerror  = (error)=>{
    console.log(error)
  }

}
function tap(){
  let enableCursor = false;  // 启用光标效果
  if (char_index.value < full_context.value.length) {
    let txt = items.value[items.value.length-1].content;
    let cursor = enableCursor ? "|" : "";
    if (enableCursor && txt.endsWith("|")) {
      txt = txt.slice(0, -1);
    }
    items.value[items.value.length-1].content = txt + full_context.value.charAt(char_index.value) + cursor;
    char_index.value = char_index.value+1;
    scrollToBottom();
    setTimeout(tap, 1000/6);  // 打字机速度控制, 每秒5个字
  }
}
async function callDify() {
  char_index.value = 0;
  full_context.value = '';
  ws.value.send(query.value)

  items.value.push({type:'user',content:query.value});
  items.value.push({type:'bot',content:''})
  ischating.value=true;
  query.value="";
  nextTick(()=>{
    scrollToBottom();
  });

  // full_context.value="现在我们有了解析好的内容, 可以看到是Markdown的格式";
  // tap()
}

async function quickChat() {
  await jianAicount();
  // await streamingChat();
  callDify()
  getAiList();
}

async function delcart(obj){
   const res=await removeCartById({id:obj.id});
  // getusercart();
   userStore.setCartList();
}

async function delall(){
   const res=await clearallUserCart({});
  //  getusercart();
    userStore.setCartList();
}
//订单相关开始
  const visibleD = ref<boolean>(false);
  const status=ref(0);
  const preorderInfo=ref({});
  
  async function goorderpage (item)  {
      //构建数据
      status.value=0;
      
      let arrs=[];
      arrs.push({
              ordertype:'3',
              typeid:item.id,
              shuliang:1
      });
      
      let  orderobj={
          title:'聊天包购买',
          orderdetails:arrs
       };
     
      //查询订单 
    
     const preinfo= await precreateOrder(orderobj);
     console.log(preinfo);
     preorderInfo.value=preinfo;

     visibleD.value = true;
     // visible.value = false;
     
  };
  function orderpaysuccess(){
       visibleD.value = false;
      
       getAiList();

   }
    function changeorderstatus(v){
       status.value = v;

   }
   
   const scrollContainer=ref(null);
   function scrollToBottom() {
      
      scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
    }
   
</script>

